﻿using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Wpf.Ui;
using Wpf.Ui.Controls;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using Point = System.Windows.Point;
using Color = System.Windows.Media.Color;
using System.Windows.Controls;
using Size = System.Windows.Size;
using System.Diagnostics;
using ImageGenerator.Helpers;
using ImageGenerator.Models;

namespace ImageGenerator.ViewModels.Pages
{
    public partial class DashboardViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<BitmapSource> _images = [];

        [ObservableProperty]
        private ObservableCollection<DataDto> _dataList = [
            //new() {
            //    TitleColor = "#f40",
            //    TitleFont="仓耳小丸子",
            //    Title="如何健康的饮食",
            //    SubTitle="",
            //    ImgPath="C:\\Windows\\Web\\Wallpaper\\ThemeC\\img31.jpg",
            //    Step="1. 每天一个苹果",
            //    StepColor="#f40",
            //    StepFont="猫啃什锦黑",
            //    StepDetail="早上起来，先喝杯温开水，保证每天吃一个苹果",
            //    StepDetailColor="DarkBlue",
            //    StepDetailFont="站酷庆科黄油体",
            //    BgImage="C:\\Windows\\Web\\touchkeyboard\\TouchKeyboardThemeLight001.jpg"
            //}
        ];

        private readonly ISnackbarService snackbarService;
        private readonly LicenseHelper lic;
        [ObservableProperty]
        private Visibility _invalid = Visibility.Collapsed;
        [ObservableProperty]
        private Visibility _valid = Visibility.Collapsed;

        public DashboardViewModel(ISnackbarService snackbarService, LicenseHelper lic)
        {
            this.snackbarService = snackbarService;
            this.lic = lic;

            if (lic.Validation.Item1 == true)
                Valid = Visibility.Visible;
            else
                Invalid = Visibility.Visible;
        }

        [RelayCommand]
        private void OnDownloadTemplate()
        {
            var dlg = new SaveFileDialog
            {
                FileName = "导入模板",
                Filter = "excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*"
            };

            if (dlg.ShowDialog() == true)
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets", "template.xlsx");
                if (File.Exists(path))
                {
                    File.Copy(path, dlg.FileName, true);
                    snackbarService.Show("提示", "模板下载成功", ControlAppearance.Success, new SymbolIcon(SymbolRegular.CheckmarkStarburst24), TimeSpan.FromSeconds(3));
                }
                else
                    snackbarService.Show("提示", "模板下载失败", ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Warning24), TimeSpan.FromSeconds(3));

            }
        }

        public IImporter Importer = new ExcelImporter();
        [RelayCommand]
        private async Task OnImportData()
        {
            var dlg = new OpenFileDialog
            {
                Filter = "excel文件(*.xlsx)|*.xlsx"
            };

            if (dlg.ShowDialog() == true)
            {
                var path = dlg.FileName;
                var import = await Importer.Import<DataDto>(path);
                if (import == null ||
                    import.Exception != null ||
                    import.RowErrors.Count > 0 ||
                    import.HasError ||
                    import.Data == null)
                {
                    snackbarService.Show("提示", "数据导入失败,请检查数据格式后重试", ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Warning24), TimeSpan.FromSeconds(3));
                }
                else
                {
                    DataList.Clear();
                    foreach (var item in import.Data)
                    {
                        item.BgImage = GetFilePath(item.BgImage);
                        item.ImgPath = GetFilePath(item.ImgPath);

                        DataList.Add(item);

                    }
                    snackbarService.Show("提示", "数据导入成功", ControlAppearance.Success, new SymbolIcon(SymbolRegular.CheckmarkStarburst24), TimeSpan.FromSeconds(3));
                }
            }
        }

        private static string GetFilePath(string img)
        {
            if (Directory.Exists(img))
            {
                var files = Directory.GetFiles(img, "*.*", SearchOption.TopDirectoryOnly)
                    .Where(x => x.EndsWith(".png") || x.EndsWith(".jpg") || x.EndsWith(".jpeg"))
                    .ToList();

                if (files.Count > 0)
                {
                    // 在文件数组中随机选择一个索引
                    Random random = new();
                    int index = random.Next(files.Count);
                    // 获取随机选择的文件的路径
                    return files[index];
                }
            }
            return img;
        }

        [ObservableProperty]
        private ObservableCollection<string> _comboBoxRatio = ["3 : 4", "9 : 16"];
        [ObservableProperty]
        private int _comboBoxRatioSelected = 0;
        [ObservableProperty]
        private int _height = 100;

        [RelayCommand]
        private void OnRatioChange()
        {
            if (ComboBoxRatioSelected == 1)
                Height = 533;
            else
                Height = 400;
        }

        [ObservableProperty]
        private SolidColorBrush _bgColor = new(Colors.LightGray);
        [ObservableProperty]
        private SolidColorBrush _titleColor = new(Colors.Red);
        [ObservableProperty]
        private SolidColorBrush _subTitleColor = new(Colors.Black);
        [ObservableProperty]
        private SolidColorBrush _stepColor = new(Colors.OrangeRed);
        [ObservableProperty]
        private SolidColorBrush _stepDetailColor = new(Colors.Black);

        [RelayCommand]
        private void OnPickColor(string type)
        {
            var dlg = new ColorDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var color = Color.FromRgb(dlg.Color.R, dlg.Color.G, dlg.Color.B);
                switch (type)
                {
                    case "Bg":
                        BgColor.Color = color;
                        break;
                    case "Title":
                        TitleColor.Color = color;
                        break;
                    case "SubTitle":
                        SubTitleColor.Color = color;
                        break;
                    case "Step":
                        StepColor.Color = color;
                        break;
                    case "StepDetail":
                        StepDetailColor.Color = color;
                        break;
                    default:
                        break;
                }
            }
        }

        [RelayCommand]
        private void OnSaveImages(ItemsControl icList)
        {
            if (lic.Validation.Item2 == null || DateTime.Now >= lic.Validation.Item2)
            {
                snackbarService.Show("提示", "软件认证已过期，请练习技术支持人员进行续期后再使用", ControlAppearance.Caution, new SymbolIcon(SymbolRegular.CheckmarkStarburst24), TimeSpan.FromSeconds(30));
                return;
            }

            if (DataList.Count == 0)
            {
                snackbarService.Show("提示", "请先根据模板导入数据", ControlAppearance.Caution, new SymbolIcon(SymbolRegular.CheckmarkStarburst24), TimeSpan.FromSeconds(3));
                return;
            }

            foreach (var item in icList.Items)
            {
                var itemModel = item as DataDto;
                var container = FindContainerForItem(icList, itemModel);
                if (container != null)
                {
                    // 渲染元素到位图
                    var dpi = 96.0; // 可以根据需要调整

                    RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)container.ActualWidth * 2, (int)container.ActualHeight * 2, dpi, dpi, PixelFormats.Pbgra32);
                    DrawingVisual drawingVisual = new();
                    using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                    {
                        VisualBrush vb = new(container);
                        drawingContext.DrawRectangle(vb, null, new Rect(new Point(), new Size(container.ActualWidth * 2, container.ActualHeight * 2)));
                    }

                    renderBitmap.Render(drawingVisual);

                    // 将位图保存为PNG文件
                    PngBitmapEncoder encoder = new();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
                    if (!File.Exists(filePath))
                        Directory.CreateDirectory(filePath);
                    var fullPath = Path.Combine(filePath, $"{itemModel.Title}_{itemModel.Step}_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.png");

                    using FileStream stream = new(fullPath, FileMode.Create);
                    encoder.Save(stream);
                }
            }

            snackbarService.Show("提示", "图片保存成功", ControlAppearance.Success, new SymbolIcon(SymbolRegular.CheckmarkStarburst24), TimeSpan.FromSeconds(3));
        }

        private FrameworkElement FindContainerForItem(ItemsControl icList, DataDto item)
        {
            var generator = icList.ItemContainerGenerator;
            var container = generator.ContainerFromItem(item) as FrameworkElement;

            if (container == null)
            {
                icList.UpdateLayout();
                container = generator.ContainerFromItem(item) as FrameworkElement;
            }

            return container;
        }

        [RelayCommand]
        private void OnOpenFolder()
        {
            var folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
            if (!File.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            Process.Start("explorer.exe", folderPath);
        }
    }
}
